import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-08-08
 * Time: 16:12
 */
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable,long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return this.time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> blockingQueue = new PriorityQueue<>();
    private static Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread(() -> {
            synchronized(locker) {
                while (true) {
                    while (blockingQueue.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask current = blockingQueue.peek();
                    if (current.getTime() <= System.currentTimeMillis()) {
                        current.run();
                        blockingQueue.poll();
                    } else {
                        try {
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
            t.start();
    }

    public void schedule(Runnable runnable,long delay) throws InterruptedException {
        synchronized(locker) {
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            blockingQueue.offer(myTimerTask);
            locker.notify();
        }
    }

}



public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                System.out.println(3000);
//            }
//        },3000);


        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> {
            System.out.println("3000");
        },3000);

        myTimer.schedule(() -> {
            System.out.println("2000");
        },2000);


        myTimer.schedule(() -> {
            System.out.println("1000");
        },1000);

        System.out.println("程序开始执行");

    }
}
